package cn.thinkluck.pattern.singleton;

import java.io.Serializable;

/**
 * @Author liutao
 * @DateTime 2024/7/14 下午9:02
 * 懒汉式单例
 */
public class LazySingleton implements Serializable {
    private static volatile LazySingleton INSTANCE = null;

    private LazySingleton() {
        /*
          防止外部通过反射调用
         */
        if (INSTANCE != null){
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }

    public static LazySingleton getInstance() {
        if (INSTANCE == null) {
            synchronized (LazySingleton.class) {
                if (INSTANCE == null) {
                    INSTANCE = new LazySingleton();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 防止通过序列化和反序列化创建多个实例
     */
    private Object readResolve() {
        return INSTANCE;
    }
}
